use std::str::FromStr;
use std::io::Write;
use std::net::{TcpListener, TcpStream};
use std::net::SocketAddr;
use std::thread;
use std::io::prelude::*;
use std::str;

fn handle_connection(stream: &mut TcpStream) {
    loop {
        let mut buf = [0;128];
        stream.read(&mut buf).expect("read data failed");
        let data = match str::from_utf8(&buf) {
            Ok(v) => v,
            Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
        };
        println!("recv data:{}",data);

        // 执行相应业务
        stream.write(b"success").expect("apply failed");
    }
}

fn main() {
    let addr: SocketAddr = SocketAddr::from_str("0.0.0.0:10248").unwrap();
    let listener = TcpListener::bind(addr).unwrap();

    println!("start server at port:10248...");
    for stream in listener.incoming() {
        println!("accept.");
        match stream {
            Err(_) => println!("listen error"),
            Ok(mut stream) => { // mut stream
                println!("connection from {} to {}",stream.peer_addr().unwrap(),stream.local_addr().unwrap());

                thread::spawn(move || {
                    handle_connection(&mut stream);
                });
            }
        }
    }
    println!("exit.");
}
